import { View, Text, ScrollView, Image } from '@tarojs/components'
import { useState, useEffect } from 'react'
import Taro, { useRouter } from '@tarojs/taro'
import './hospital-detail.scss'

// 定义类型接口
interface Doctor {
  id: string
  name: string
  title: string
  avatar: string
  specialties: string[]
  description: string
}

interface Product {
  id: string
  title: string
  price: number
  originalPrice: number
  saved: number
  image: string
  tags: string[]
}

interface Review {
  id: string
  userName: string
  avatar: string
  rating: number
  content: string
  date: string
  images: string[]
}

interface HospitalData {
  _id: string
  name: string
  logo: string
  rating: number
  services: number
  reviews: number
  doctors: number
  location: string
  city: string
  province: string
  area: string
  tag: string
  category: string
  isHot: boolean
  viewCount: number
  createTime: string
  description: string
  address: string
  phone: string
  doctorsList: Doctor[]
  productsList: Product[]
  reviewsList: Review[]
  // 虚拟数据字段
  introduction: string
  environmentImages: string[]
  honorCertificates: string[]
  medicalEquipment: string[]
  serviceHours: string
  transportation: string
  facilities: string[]
}

const HospitalDetail = () => {
  const router = useRouter()
  const [hospitalData, setHospitalData] = useState<HospitalData | null>(null)
  const [loading, setLoading] = useState(true)
  const [activeTab, setActiveTab] = useState('介绍')

  useEffect(() => {
    const { id } = router.params
    
    if (id) {
      fetchHospitalData(id)
    } else {
      Taro.showToast({
        title: '未找到医院信息',
        icon: 'error'
      })
      setLoading(false)
    }
  }, [router.params])

  // 获取医院数据
  const fetchHospitalData = async (hospitalId: string) => {
    try {
      setLoading(true)
      console.log('开始获取医院数据，ID:', hospitalId)
      
      const response = await Taro.request({
        url: `http://localhost:3000/cosmetic/hospitals/${hospitalId}`,
        method: 'GET',
        timeout: 10000
      })

      console.log('API响应:', response)

      if (response.statusCode === 200 && response.data && response.data.success) {
        const hospital = response.data.data
        console.log('获取到的医院数据:', hospital)
        
        // 补充虚拟数据
        const enhancedHospital: HospitalData = {
          ...hospital,
          description: hospital.description || `${hospital.name}是一家专业的医疗美容医院，拥有先进的医疗设备和专业的医生团队。我们致力于为客户提供安全、有效、个性化的医疗美容服务。`,
          address: hospital.address || '上海市静安区南京西路1686号',
          phone: hospital.phone || '400-123-4567',
          introduction: `${hospital.name}成立于2010年，是一家集医疗、教学、科研为一体的综合性医疗美容机构。医院环境优雅，设备先进，医生经验丰富，是您进行医疗美容的理想选择。`,
          environmentImages: [
            'https://images.unsplash.com/photo-1586773860418-d37222d8fce3?w=750&h=400&fit=crop',
            'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=750&h=400&fit=crop',
            'https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=750&h=400&fit=crop'
          ],
          honorCertificates: [
            'https://images.unsplash.com/photo-1586773860418-d37222d8fce3?w=300&h=200&fit=crop',
            'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=300&h=200&fit=crop'
          ],
          medicalEquipment: ['激光美容仪', '超声刀', '热玛吉', '水光注射仪', '射频紧肤仪'],
          serviceHours: '周一至周日 09:00 - 20:00',
          transportation: '地铁1号线XX站A口出，步行5分钟',
          facilities: ['VIP病房', '无菌手术室', '激光治疗室', '皮肤管理中心', '休息区'],
          doctorsList: hospital.doctorsList || [
            {
              id: 'doc001',
              name: '李美丽',
              title: '主任医师',
              avatar: 'https://images.unsplash.com/photo-1559839734-2b71ea197ec2?w=100&h=100&fit=crop&crop=face',
              specialties: ['眼部整形', '面部轮廓', '注射美容'],
              description: '李医生在医疗美容领域拥有超过15年的临床经验，擅长各类整形手术和微整形注射。'
            },
            {
              id: 'doc002',
              name: '张医生',
              title: '副主任医师',
              avatar: 'https://images.unsplash.com/photo-1612349317150-e413f6a5b16d?w=100&h=100&fit=crop&crop=face',
              specialties: ['激光美容', '皮肤管理', '抗衰老'],
              description: '张医生专注于激光美容和皮肤管理，在抗衰老治疗方面有独到见解。'
            },
            {
              id: 'doc003',
              name: '王医生',
              title: '主治医师',
              avatar: 'https://images.unsplash.com/photo-1594824475544-3c5b3c5b3c5b?w=100&h=100&fit=crop&crop=face',
              specialties: ['微整形', '玻尿酸填充', '瘦脸针'],
              description: '王医生在微整形领域经验丰富，尤其擅长玻尿酸填充和瘦脸针注射。'
            }
          ],
          productsList: hospital.productsList || [
            {
              id: 'prod001',
              title: '水光针美白嫩肤',
              price: 1580,
              originalPrice: 2280,
              saved: 700,
              image: 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=300&h=200&fit=crop',
              tags: ['美白', '嫩肤', '补水']
            },
            {
              id: 'prod002',
              title: '玻尿酸深层补水保湿',
              price: 1280,
              originalPrice: 1980,
              saved: 700,
              image: 'https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=300&h=200&fit=crop',
              tags: ['补水', '保湿', '抗衰']
            },
            {
              id: 'prod003',
              title: '激光祛斑美白',
              price: 980,
              originalPrice: 1580,
              saved: 600,
              image: 'https://images.unsplash.com/photo-1586773860418-d37222d8fce3?w=300&h=200&fit=crop',
              tags: ['祛斑', '美白', '嫩肤']
            }
          ],
          reviewsList: hospital.reviewsList || [
            {
              id: 'rev001',
              userName: '张女士',
              avatar: 'https://images.unsplash.com/photo-1494790108755-2616b612b786?w=50&h=50&fit=crop&crop=face',
              rating: 5,
              content: '服务很好，医生很专业，效果满意！医院环境也很舒适。',
              date: '2024-01-15',
              images: ['https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=100&h=100&fit=crop']
            },
            {
              id: 'rev002',
              userName: '李女士',
              avatar: 'https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=50&h=50&fit=crop&crop=face',
              rating: 4,
              content: '医生技术不错，价格也比较合理，推荐给大家。',
              date: '2024-01-10',
              images: []
            },
            {
              id: 'rev003',
              userName: '王女士',
              avatar: 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?w=50&h=50&fit=crop&crop=face',
              rating: 5,
              content: '做了水光针，效果很明显，皮肤变得水润有光泽。',
              date: '2024-01-08',
              images: ['https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=100&h=100&fit=crop']
            }
          ]
        }
        
        setHospitalData(enhancedHospital)
        console.log('医院详情数据:', enhancedHospital)
      } else {
        console.error('API响应格式错误:', response)
        throw new Error(`API响应错误: ${response.statusCode} - ${response.data?.message || '未知错误'}`)
      }
    } catch (error) {
      console.error('获取医院数据失败:', error)
      
      // 如果API调用失败，使用虚拟数据
      const mockHospital: HospitalData = {
        _id: hospitalId,
        name: '北京美莱医疗美容医院',
        logo: 'https://images.unsplash.com/photo-1586773860418-d37222d8fce3?w=100&h=100&fit=crop',
        rating: 4.9,
        services: 25800,
        reviews: 5680,
        doctors: 35,
        location: '北京市朝阳区建国门外大街1号',
        city: '北京市',
        province: '北京市',
        area: '朝阳区',
        tag: '北京市医美人气热销榜第1名',
        category: '热门',
        isHot: true,
        viewCount: 12800,
        createTime: '2024-01-15T08:00:00.000Z',
        description: '北京美莱医疗美容医院是一家专业的医疗美容医院，拥有先进的医疗设备和专业的医生团队。',
        address: '北京市朝阳区建国门外大街1号',
        phone: '400-123-4567',
        introduction: '北京美莱医疗美容医院成立于2010年，是一家集医疗、教学、科研为一体的综合性医疗美容机构。',
        environmentImages: [
          'https://images.unsplash.com/photo-1586773860418-d37222d8fce3?w=750&h=400&fit=crop',
          'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=750&h=400&fit=crop',
          'https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=750&h=400&fit=crop'
        ],
        honorCertificates: [
          'https://images.unsplash.com/photo-1586773860418-d37222d8fce3?w=300&h=200&fit=crop',
          'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=300&h=200&fit=crop'
        ],
        medicalEquipment: ['激光美容仪', '超声刀', '热玛吉', '水光注射仪', '射频紧肤仪'],
        serviceHours: '周一至周日 09:00 - 20:00',
        transportation: '地铁1号线建国门站A口出，步行5分钟',
        facilities: ['VIP病房', '无菌手术室', '激光治疗室', '皮肤管理中心', '休息区'],
        doctorsList: [
          {
            id: 'doc001',
            name: '李美丽',
            title: '主任医师',
            avatar: 'https://images.unsplash.com/photo-1559839734-2b71ea197ec2?w=100&h=100&fit=crop&crop=face',
            specialties: ['眼部整形', '面部轮廓', '注射美容'],
            description: '李医生在医疗美容领域拥有超过15年的临床经验，擅长各类整形手术和微整形注射。'
          },
          {
            id: 'doc002',
            name: '张医生',
            title: '副主任医师',
            avatar: 'https://images.unsplash.com/photo-1612349317150-e413f6a5b16d?w=100&h=100&fit=crop&crop=face',
            specialties: ['激光美容', '皮肤管理', '抗衰老'],
            description: '张医生专注于激光美容和皮肤管理，在抗衰老治疗方面有独到见解。'
          },
          {
            id: 'doc003',
            name: '王医生',
            title: '主治医师',
            avatar: 'https://images.unsplash.com/photo-1594824475544-3c5b3c5b3c5b?w=100&h=100&fit=crop&crop=face',
            specialties: ['微整形', '玻尿酸填充', '瘦脸针'],
            description: '王医生在微整形领域经验丰富，尤其擅长玻尿酸填充和瘦脸针注射。'
          }
        ],
        productsList: [
          {
            id: 'prod001',
            title: '水光针美白嫩肤',
            price: 1580,
            originalPrice: 2280,
            saved: 700,
            image: 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=300&h=200&fit=crop',
            tags: ['美白', '嫩肤', '补水']
          },
          {
            id: 'prod002',
            title: '玻尿酸深层补水保湿',
            price: 1280,
            originalPrice: 1980,
            saved: 700,
            image: 'https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=300&h=200&fit=crop',
            tags: ['补水', '保湿', '抗衰']
          },
          {
            id: 'prod003',
            title: '激光祛斑美白',
            price: 980,
            originalPrice: 1580,
            saved: 600,
            image: 'https://images.unsplash.com/photo-1586773860418-d37222d8fce3?w=300&h=200&fit=crop',
            tags: ['祛斑', '美白', '嫩肤']
          }
        ],
        reviewsList: [
          {
            id: 'rev001',
            userName: '张女士',
            avatar: 'https://images.unsplash.com/photo-1494790108755-2616b612b786?w=50&h=50&fit=crop&crop=face',
            rating: 5,
            content: '服务很好，医生很专业，效果满意！医院环境也很舒适。',
            date: '2024-01-15',
            images: ['https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=100&h=100&fit=crop']
          },
          {
            id: 'rev002',
            userName: '李女士',
            avatar: 'https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=50&h=50&fit=crop&crop=face',
            rating: 4,
            content: '医生技术不错，价格也比较合理，推荐给大家。',
            date: '2024-01-10',
            images: []
          },
          {
            id: 'rev003',
            userName: '王女士',
            avatar: 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?w=50&h=50&fit=crop&crop=face',
            rating: 5,
            content: '做了水光针，效果很明显，皮肤变得水润有光泽。',
            date: '2024-01-08',
            images: ['https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=100&h=100&fit=crop']
          }
        ]
      }
      
      setHospitalData(mockHospital)
      Taro.showToast({
        title: '使用虚拟数据',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }

  // 处理咨询
  const handleConsultation = () => {
    if (!hospitalData) return
    
    const hospitalId = hospitalData.id || hospitalData._id || ''
    const hospitalName = encodeURIComponent(hospitalData.name || '')
    const query = `?targetType=hospital&targetId=${hospitalId}&targetName=${hospitalName}`
    console.log('hospital detail consult -> navigateTo', `/pages/chat/chat${query}`)
    Taro.navigateTo({ url: `/pages/chat/chat${query}` })
      .catch(() => {
        Taro.showToast({
          title: '无法打开聊天页',
          icon: 'none'
        })
      })
  }

  // 处理预约
  const handleBooking = () => {
    Taro.showToast({
      title: '正在跳转预约...',
      icon: 'loading'
    })
  }

  // 处理产品点击
  const handleProductClick = (product: Product) => {
    console.log('点击产品:', product)
    Taro.navigateTo({
      url: `/packageB/pages/product-detail/product-detail?id=${product.id}`
    })
  }

  if (loading) {
    return (
      <View className='hospital-detail'>
        <View className='loading-container'>
          <Text>加载中...</Text>
        </View>
      </View>
    )
  }

  if (!hospitalData) {
    return (
      <View className='hospital-detail'>
        <View className='error-container'>
          <Text>医院信息不存在</Text>
        </View>
      </View>
    )
  }

  return (
    <View className='hospital-detail'>
      <ScrollView className='content' scrollY>
        {/* 医院基本信息 */}
        <View className='hospital-info'>
          <View className='hospital-header'>
            <View className='hospital-logo'>
              <Image 
                src={hospitalData.logo || 'https://images.unsplash.com/photo-1586773860418-d37222d8fce3?w=100&h=100&fit=crop'} 
                className='logo-image'
                mode='aspectFill'
              />
            </View>
            <View className='hospital-details'>
              <Text className='hospital-name'>{hospitalData.name}</Text>
              <View className='hospital-rating'>
                <Text className='rating'>★ {hospitalData.rating || 4.8}</Text>
                <Text className='services'>服务人次 {hospitalData.services || 1200}</Text>
                <Text className='reviews'>评价 {hospitalData.reviews || 500}</Text>
              </View>
              <Text className='hospital-tag'>{hospitalData.tag || '北京市医美医院人气热销榜第1名'}</Text>
            </View>
          </View>
          
          <View className='action-buttons'>
            <View className='action-btn consult-btn' onClick={handleConsultation}>
              <Text>私信咨询</Text>
            </View>
            <View className='action-btn book-btn' onClick={handleBooking}>
              <Text>立即预约</Text>
            </View>
          </View>
        </View>

        {/* 标签页导航 */}
        <View className='tab-nav'>
          <View 
            className={`tab-item ${activeTab === '介绍' ? 'active' : ''}`}
            onClick={() => setActiveTab('介绍')}
          >
            <Text>医院介绍</Text>
          </View>
          <View 
            className={`tab-item ${activeTab === '项目' ? 'active' : ''}`}
            onClick={() => setActiveTab('项目')}
          >
            <Text>热门项目</Text>
          </View>
          <View 
            className={`tab-item ${activeTab === '医生' ? 'active' : ''}`}
            onClick={() => setActiveTab('医生')}
          >
            <Text>医生团队</Text>
          </View>
          <View 
            className={`tab-item ${activeTab === '评价' ? 'active' : ''}`}
            onClick={() => setActiveTab('评价')}
          >
            <Text>用户评价</Text>
          </View>
        </View>

        {/* 标签页内容 */}
        <View className='tab-content'>
          {/* 医院介绍 */}
          {activeTab === '介绍' && (
            <View className='hospital-intro'>
              <View className='intro-section'>
                <Text className='section-title'>医院简介</Text>
                <Text className='section-content'>
                  {hospitalData.introduction || hospitalData.description || `${hospitalData.name}是一家专业的医疗美容医院，拥有先进的医疗设备和专业的医生团队。`}
                </Text>
              </View>
              
              <View className='intro-section'>
                <Text className='section-title'>医院特色</Text>
                <View className='features'>
                  <View className='feature-item'>
                    <Text className='feature-icon'>🏥</Text>
                    <Text className='feature-text'>专业医疗团队</Text>
                  </View>
                  <View className='feature-item'>
                    <Text className='feature-icon'>🔬</Text>
                    <Text className='feature-text'>先进医疗设备</Text>
                  </View>
                  <View className='feature-item'>
                    <Text className='feature-icon'>💎</Text>
                    <Text className='feature-text'>优质服务体验</Text>
                  </View>
                  <View className='feature-item'>
                    <Text className='feature-icon'>🛡️</Text>
                    <Text className='feature-text'>安全保障体系</Text>
                  </View>
                </View>
              </View>
              
              <View className='intro-section'>
                <Text className='section-title'>医院地址</Text>
                <Text className='section-content'>
                  {hospitalData.address || '北京市朝阳区xxx路xxx号'}
                </Text>
              </View>

              <View className='intro-section'>
                <Text className='section-title'>联系电话</Text>
                <Text className='section-content'>
                  {hospitalData.phone || '400-123-4567'}
                </Text>
              </View>

              <View className='intro-section'>
                <Text className='section-title'>服务时间</Text>
                <Text className='section-content'>
                  {hospitalData.serviceHours || '周一至周日 09:00 - 20:00'}
                </Text>
              </View>

              <View className='intro-section'>
                <Text className='section-title'>交通指南</Text>
                <Text className='section-content'>
                  {hospitalData.transportation || '地铁1号线XX站A口出，步行5分钟'}
                </Text>
              </View>

              {hospitalData.facilities && hospitalData.facilities.length > 0 && (
                <View className='intro-section'>
                  <Text className='section-title'>特色设施</Text>
                  <View className='facilities-list'>
                    {hospitalData.facilities.map((facility, index) => (
                      <Text key={index} className='facility-item'>{facility}</Text>
                    ))}
                  </View>
                </View>
              )}

              {hospitalData.medicalEquipment && hospitalData.medicalEquipment.length > 0 && (
                <View className='intro-section'>
                  <Text className='section-title'>医疗设备</Text>
                  <View className='equipment-list'>
                    {hospitalData.medicalEquipment.map((equipment, index) => (
                      <Text key={index} className='equipment-item'>{equipment}</Text>
                    ))}
                  </View>
                </View>
              )}
            </View>
          )}

          {/* 热门项目 */}
          {activeTab === '项目' && (
            <View className='hot-projects'>
              <View className='project-grid'>
                {hospitalData.productsList && hospitalData.productsList.length > 0 ? (
                  hospitalData.productsList.map((product, index) => (
                    <View 
                      key={product.id || `product-${index}`} 
                      className='project-card'
                      onClick={() => handleProductClick(product)}
                    >
                      <View className='project-image'>
                        <Image 
                          src={product.image || 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=300&h=200&fit=crop'} 
                          className='image'
                          mode='aspectFill'
                        />
                      </View>
                      <View className='project-info'>
                        <Text className='project-title'>{product.title || '项目名称'}</Text>
                        {product.tags && product.tags.length > 0 && (
                          <View className='project-tags'>
                            {product.tags.map((tag, tagIndex) => (
                              <Text key={tagIndex} className='project-tag'>{tag}</Text>
                            ))}
                          </View>
                        )}
                        <View className='project-price'>
                          <Text className='current-price'>¥{product.price || 0}</Text>
                          <Text className='original-price'>¥{product.originalPrice || (product.price || 0) + 500}</Text>
                        </View>
                        <Text className='saved-price'>已省¥{product.saved || 500}</Text>
                      </View>
                    </View>
                  ))
                ) : (
                  <View className='no-projects'>
                    <Text>暂无项目信息</Text>
                  </View>
                )}
              </View>
            </View>
          )}

          {/* 医生团队 */}
          {activeTab === '医生' && (
            <View className='doctor-team'>
              <View className='doctor-list'>
                {hospitalData.doctorsList && hospitalData.doctorsList.length > 0 ? (
                  hospitalData.doctorsList.map((doctor, index) => (
                    <View key={doctor.id || `doctor-${index}`} className='doctor-card'>
                      <View className='doctor-avatar'>
                        <Image 
                          src={doctor.avatar || 'https://images.unsplash.com/photo-1559839734-2b71ea197ec2?w=100&h=100&fit=crop&crop=face'} 
                          className='avatar-image'
                          mode='aspectFill'
                        />
                      </View>
                      <View className='doctor-info'>
                        <Text className='doctor-name'>{doctor.name || '医生姓名'}</Text>
                        <Text className='doctor-title'>{doctor.title || '主任医师'}</Text>
                        <View className='doctor-specialties'>
                          {doctor.specialties && Array.isArray(doctor.specialties) && doctor.specialties.length > 0 ? (
                            doctor.specialties.map((specialty, idx) => (
                              <Text key={`specialty-${idx}`} className='specialty-tag'>{specialty}</Text>
                            ))
                          ) : (
                            <Text className='specialty-tag'>专业医生</Text>
                          )}
                        </View>
                        {doctor.description && (
                          <Text className='doctor-description'>{doctor.description}</Text>
                        )}
                      </View>
                    </View>
                  ))
                ) : (
                  <View className='no-doctors'>
                    <Text>暂无医生信息</Text>
                  </View>
                )}
              </View>
            </View>
          )}

          {/* 用户评价 */}
          {activeTab === '评价' && (
            <View className='user-reviews'>
              <View className='review-list'>
                {hospitalData.reviewsList && hospitalData.reviewsList.length > 0 ? (
                  hospitalData.reviewsList.map((review, index) => (
                    <View key={review.id || `review-${index}`} className='review-card'>
                      <View className='review-header'>
                        <View className='reviewer-info'>
                          <Image 
                            src={review.avatar || 'https://images.unsplash.com/photo-1494790108755-2616b612b786?w=50&h=50&fit=crop&crop=face'} 
                            className='reviewer-avatar'
                            mode='aspectFill'
                          />
                          <View className='reviewer-details'>
                            <Text className='reviewer-name'>{review.userName || '匿名用户'}</Text>
                            <View className='review-rating'>
                              {[1, 2, 3, 4, 5].map(star => (
                                <Text key={`star-${star}`} className={`star ${star <= (review.rating || 0) ? 'filled' : ''}`}>
                                  ★
                                </Text>
                              ))}
                            </View>
                          </View>
                        </View>
                        <Text className='review-date'>{review.date || '2024-01-15'}</Text>
                      </View>
                      <Text className='review-content'>{review.content || '服务很好，医生很专业，效果满意！'}</Text>
                      {review.images && review.images.length > 0 && (
                        <View className='review-images'>
                          {review.images.map((image, imgIndex) => (
                            <Image 
                              key={`review-img-${imgIndex}`} 
                              src={image} 
                              className='review-image'
                              mode='aspectFill'
                            />
                          ))}
                        </View>
                      )}
                    </View>
                  ))
                ) : (
                  <View className='no-reviews'>
                    <Text>暂无用户评价</Text>
                  </View>
                )}
              </View>
            </View>
          )}
        </View>
      </ScrollView>
    </View>
  )
}

export default HospitalDetail
